package com.nari.ncps.screen.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.DryportProdoperFluxPlan;
import com.nari.ncps.screen.entity.dryport.DryportProdoperGoodsSend;
import com.nari.ncps.screen.entity.dryport.DryportProdoperNonCoal;
import com.nari.ncps.screen.mapper.dryport.DryportProdoperGoodsSendMapper;
import com.nari.ncps.screen.mapper.dryport.DryportProdoperNonCoalMapper;
import com.nari.ncps.screen.service.dryport.DryportProdoperGoodsSendService;
import com.nari.ncps.screen.vo.dryport.FluxPlanVO;
import com.nari.ncps.screen.vo.dryport.GoodsSendVO;
import com.nari.ncps.screen.vo.wholeproduct.RailwayGoodsSendVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 货物发送情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-09-25
 */
@Service
public class DryportProdoperGoodsSendServiceImpl extends ServiceImpl<DryportProdoperGoodsSendMapper, DryportProdoperGoodsSend> implements DryportProdoperGoodsSendService {

    @Autowired
    private DryportProdoperGoodsSendMapper goodsSendMapper;

    @Autowired
    private DryportProdoperNonCoalMapper dryportProdoperNonCoalMapper;

    @Override
    public List<DryportProdoperGoodsSend> getMonthlyStatsByYear(Integer year) {
        return goodsSendMapper.getMonthlyStatsByYear(year);
    }

    @Override
    public List<DryportProdoperGoodsSend> getLatestMonthlyStats() {
        return goodsSendMapper.getLatestMonthlyStats();
    }

    @Override
    public List<DryportProdoperGoodsSend> getStatsByYearAndMonth(Integer year, Integer month) {
        return goodsSendMapper.getStatsByYearAndMonth(year, month);
    }

    @Override
    public DryportProdoperGoodsSend getStatsByDate(Integer year, Integer month, Integer day) {
        return goodsSendMapper.getStatsByDate(year, month, day);
    }

    @Override
    public List<RailwayGoodsSendVO> getRailwayGoodsSendAnnual(Integer year) {
        List<RailwayGoodsSendVO> resultList = new ArrayList<>();
        //TODO 以下代码为应急新增，后期真数据进来再改
//        LambdaQueryWrapper<DryportProdoperGoodsSend> query = new LambdaQueryWrapper<>();
//        query.eq(DryportProdoperGoodsSend::getOrgCode, "100360")
//                .eq(DryportProdoperGoodsSend::getDateType, 0);
//        List<DryportProdoperGoodsSend> dataList = this.list(query);
//        for (DryportProdoperGoodsSend data : dataList) {
//            RailwayGoodsSendVO vo = new RailwayGoodsSendVO();
//            vo.setYear(data.getYear());
//            vo.setRailwayPlannedVolume(data.getGoodsSendPlan());
//            vo.setRailwayCompletedVolume(data.getGoodsSendAc());
//            vo.setYoyRate(data.getGoodsSendCompRate());
//            resultList.add(vo);
//        }
        //RailwayGoodsSendVO vo = new RailwayGoodsSendVO();
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        // 查询最近5年的数据
        for (int i = 4; i > -1; i--) {
            int targetYear = currentYear - i;

            // 查询目标年份的所有月份数据
            LambdaQueryWrapper<DryportProdoperGoodsSend> query = new LambdaQueryWrapper<>();
            query.eq(DryportProdoperGoodsSend::getYear, targetYear);

            //如果是当前年份，只查询到当前月份
            if (targetYear == currentYear) {
                query.le(DryportProdoperGoodsSend::getMonth, currentMonth);
            }

            List<DryportProdoperGoodsSend> yearDataList = this.list(query);

            if (!yearDataList.isEmpty()) {
                RailwayGoodsSendVO vo = new RailwayGoodsSendVO();
                vo.setYear(targetYear);

                // 汇总年度计划量和完成量（累加各月数据）
                BigDecimal totalPlan = yearDataList.stream()
                        .map(DryportProdoperGoodsSend::getGoodsSendPlan)
                        .filter(plan -> plan != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                BigDecimal totalCompleted = yearDataList.stream()
                        .map(DryportProdoperGoodsSend::getGoodsSendAc)
                        .filter(ac -> ac != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                vo.setRailwayPlannedVolume(totalPlan.setScale(2, RoundingMode.HALF_UP));
                vo.setRailwayCompletedVolume(totalCompleted.setScale(2, RoundingMode.HALF_UP));

                // 计算同比率：需要去年同期的完成量
                int lastYear = targetYear - 1;
                LambdaQueryWrapper<DryportProdoperGoodsSend> lastYearQuery = new LambdaQueryWrapper<>();
                lastYearQuery.eq(DryportProdoperGoodsSend::getYear, lastYear);

                // 如果是当前年份，去年也只查询到对应的月份
                if (targetYear == currentYear) {
                    lastYearQuery.le(DryportProdoperGoodsSend::getMonth, currentMonth);
                }

                List<DryportProdoperGoodsSend> lastYearDataList = this.list(lastYearQuery);

                if (!lastYearDataList.isEmpty()) {
                    BigDecimal lastYearCompleted = lastYearDataList.stream()
                            .map(DryportProdoperGoodsSend::getGoodsSendAc)
                            .filter(ac -> ac != null)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    // 同比率(%) = (今年完成量 - 去年完成量) / 去年完成量 * 100
                    if (lastYearCompleted.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal yoyRate = totalCompleted.subtract(lastYearCompleted)
                                .divide(lastYearCompleted, 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal("100"))
                                .setScale(2, RoundingMode.HALF_UP);
                        vo.setYoyRate(yoyRate);
                    }
                }

                resultList.add(vo);
            }
            else{
                RailwayGoodsSendVO vo = new RailwayGoodsSendVO();
                vo.setYear(targetYear);

                resultList.add(vo);
            }
        }

        return resultList;
    }

    @Override
    public List<DryportProdoperGoodsSend> getLatest30DaysStats() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算30天前的日期
        LocalDate thirtyDaysAgo = currentDate.minusDays(29);

        // 查询最近30天的数据，按日期从小到大排序
        LambdaQueryWrapper<DryportProdoperGoodsSend> query = new LambdaQueryWrapper<>();
        query.eq(DryportProdoperGoodsSend::getDateType, 2);
        query.ge(DryportProdoperGoodsSend::getYear, thirtyDaysAgo.getYear())
                .ge(DryportProdoperGoodsSend::getMonth, thirtyDaysAgo.getMonthValue())
                .ge(DryportProdoperGoodsSend::getDay, thirtyDaysAgo.getDayOfMonth())
                .orderByAsc(DryportProdoperGoodsSend::getYear)
                .orderByAsc(DryportProdoperGoodsSend::getBid)
                .orderByAsc(DryportProdoperGoodsSend::getMonth)
                .orderByAsc(DryportProdoperGoodsSend::getDay);

        List<DryportProdoperGoodsSend> dataList = this.list(query);

        // 如果数据库中的数据不足30条，返回所有数据
        // 如果超过30条，只返回最近30条
        if (dataList.size() > 30) {
            return dataList.subList(dataList.size() - 30, dataList.size());
        }

        return dataList;
    }

    @Override
    public List<GoodsSendVO> getGoodsSendStatistics(Integer year) {
        // 获取最近30天的Entity数据
        List<DryportProdoperGoodsSend> entityList = getLatest30DaysStats();

        // 转换为VO对象
        List<GoodsSendVO> data = new ArrayList<>();
        if (entityList != null && !entityList.isEmpty()) {
            for (DryportProdoperGoodsSend entity : entityList) {
                GoodsSendVO vo = new GoodsSendVO();
//                vo.setDate(entity.getDate());
                vo.setYear(String.valueOf(entity.getYear()));
                vo.setMonth(String.valueOf(entity.getMonth()));
                vo.setDay(String.valueOf(entity.getDay()));
                vo.setDate(entity.getYear()+"-"+entity.getMonth()+"-"+entity.getDay());
                vo.setGoodsSendPlan(entity.getGoodsSendPlan());
                vo.setGoodsSendAc(entity.getGoodsSendAc() == null ?  BigDecimal.ZERO :
                        entity.getGoodsSendAc().divide(new BigDecimal(10000))
                                .setScale(2, BigDecimal.ROUND_HALF_UP) );

                if(entity.getGoodsSendCompRate()!=null){
                    vo.setGoodsSendCompRate(entity.getGoodsSendCompRate());
                }else{
//                    vo.setGoodsSendCompRate(entity.getGoodsSendAc().divide(entity.getGoodsSendPlan(), 4, BigDecimal.ROUND_HALF_UP)
//                            .multiply(new BigDecimal("100")));
                }
                data.add(vo);
            }
        }

        return data;
    }

    @Override
    public List<FluxPlanVO> getGoodsSendNocoalPlan(Integer year) {

        List<FluxPlanVO> voList = new ArrayList<>();
        // 获取当前日期和11个月前的日期（共5个月）
        LocalDate currentDate = LocalDate.now();
        LocalDate elevenMonthsAgo = currentDate.minusMonths(5);

        // 格式化日期为 statistic_time 的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String startDateStr = elevenMonthsAgo.format(formatter);
        String endDateStr = currentDate.format(formatter);

        System.out.println("查询日期范围: " + startDateStr + " - " + endDateStr);

        // 构建查询条件
        LambdaQueryWrapper<DryportProdoperNonCoal> lqw = new LambdaQueryWrapper<>();

        lqw.eq(DryportProdoperNonCoal::getOrgCode, "100360")
                .eq(DryportProdoperNonCoal::getDelFlag, 0)
                .eq(DryportProdoperNonCoal::getDateType,1)
                .ge(DryportProdoperNonCoal::getStatisticTime, startDateStr)
                .le(DryportProdoperNonCoal::getStatisticTime, endDateStr);

        // 执行查询
        List<DryportProdoperNonCoal> entityList = dryportProdoperNonCoalMapper.selectList(lqw);

        // 将实体转换为VO
        if (entityList != null && !entityList.isEmpty()) {
            for(DryportProdoperNonCoal entity : entityList) {
                FluxPlanVO vo = new FluxPlanVO();
                BeanUtils.copyProperties(entity, vo);
                vo.setFluxPlanned(entity.getNonCoalPlanned());
                vo.setFluxCompleted(entity.getNonCoalCompleted());
                vo.setCompletionRate(entity.getNonCoalCompletionRate());
                voList.add(vo);
            }
        }

        return voList;
    }
}
